import json
import os
import time,datetime

from aijia import settings
from django.http import HttpResponse,JsonResponse,HttpResponseBadRequest
from django.core.cache import cache
from django.views import View
from apps.houses.models import Area,Facility,HouseImage,House
from apps.users.models import User
from apps.orders.models import Order
from utils.relogin import LoginRequiredJSONMixin
from apps.users.views import QNYUN_URL
from utils.qiniuyun import bucket_name
domain_name = QNYUN_URL
bucked_name = bucket_name  # 空间名
def index(request):

    return HttpResponse("OK")
# TODO 1.城区列表 √
class AreaView(View):
    def get(self,request):
        """
        需求:
                获取城区信息
        前端:
                发送一个ajax[axios]请求
        后端:

            请求:
                        GET     areas/          JSON
            业务逻辑:
                    1. 查询数据库
                    2. 将查询结果集遍历 转换为字典字典数据
                    3. 返回响应
            响应
                {
                "errmsg": "获取成功",
                "errno": "0",
                "data": [
                    {
                        "aid": 1,
                        "aname": "东城区"
                    },
                    {
                        "aid": 2,
                        "aname": "西城区"
                    },
                    {
                        "aid": 3,
                        "aname": "朝阳区"
                    }
                ]
            }

        """
        # 先读取缓存
        data_list = cache.get('district')

        # 判断缓存是否有数据
        if data_list is None:
            # 如果没有缓存数据,则重新查询
            # 1. 查询数据库
            areas = Area.objects.all()

            data_list = []
            # 2. 将查询结果集遍历 转换为字典字典数据
            for area in areas:
                data_list.append({
                    'aid': area.id,
                    'aname': area.name
                })

            # 这里缓存
            # cache.set(key,value,seconds)
            # 过期时长 要结合具体的需求 district 城区名
            cache.set('district', data_list, 24 * 3600)

        # 3. 返回响应
        return JsonResponse({"errmsg": "获取成功",
                             "errno": "0",
                             "data": data_list})
# TODO 2.发布房源 POST √
# TODO 6.房屋数据搜索 GET
# TODO 验证是否登录待会儿写
from django.core.paginator import Paginator, EmptyPage
class PublishHouseView(View):
    def post(self,request):
        # 1. 接收参数
        data_body = request.body
        data = data_body.decode()
        json_dict = json.loads(data)
        # 2. 提取参数
        title = json_dict.get('title')
        price = json_dict.get('price',1000)
        area_id = json_dict.get('area_id',1)
        address = json_dict.get('address','中国')
        room_count = json_dict.get('room_count',5)
        acreage	 = json_dict.get('acreage',123)
        unit = json_dict.get('unit',15)
        capacity = json_dict.get('capacity',1)
        beds = json_dict.get('beds','三室二厅')
        deposit = json_dict.get('deposit',123)
        min_days = json_dict.get('min_days',0)
        max_days = json_dict.get('max_days',12)
        facility_list = json_dict.get('facility',[1,2])

        # 3. 验证参数
        if not all([title, price, area_id, address, room_count, acreage,unit,beds,capacity,deposit,min_days,max_days,facility_list]):
            return JsonResponse({'code': 400, 'errmsg': '参数缺少'})
        # TODO 验证该用户存不存在,待会儿再写
        # try:
        #     area = Area.objects.get(id = area_id)
        # except User.DoesNotExist:
        #     return JsonResponse({'code':400,'errmsg':'没有该用户'})

        # 4. 数据入库
        house = House.objects.create(
            # TODO 稍后修改
            user=request.user,
            # user=request.user,
            area = Area.objects.get(id=area_id),
            title = title,
            price = price,  # 单价，单位：分
            address = address,  # 地址
            room_count = room_count,  # 房间数目
            acreage = acreage,  # 房屋面积
            unit = unit,  # 房屋单元， 如几室几厅
            capacity = capacity,  # 房屋容纳的人数
            beds = beds,  # 房屋床铺的配置
            deposit = deposit,  # 房屋押金
            min_days = min_days,  # 最少入住天数
            max_days = max_days  # 最多入住天数，0表示不限制
        )
        for facility_id in facility_list:
            try:
                facility1 = Facility.objects.get(id = facility_id)
            except Facility.DoesNotExist:
                return JsonResponse({'code': 400, 'errmsg': '没有该设施'})
            house.facility.add(facility1)

        # 5. 返回响应
        return JsonResponse({
                            "errno": "0",
                            "errmsg": "发布成功",
                            "data": {
                                "house_id": house.id}
                            })
    def get(self,request):
        data = request.GET
        time1 = time.strftime("%Y-%m-%d", time.localtime())
        aid = data.get('aid')
        sd = data.get('sd')
        ed = data.get('ed')
        sk = data.get('sk')
        p = data.get('p',1)
        if not sd:
            sd = time1
        total_page = 0
        global houses_order
        houses_order = 0
        if not all([sd,sk,p]):
            return JsonResponse({"errno": "400", "errmsg": "按照条件查询"})
        if all([aid,ed]):
            # 全为真
            try:
                house = House.objects.filter(area_id=aid)
            except Area.DoesNotExist:
                return JsonResponse({'errno': 400, 'errmsg': '没有房源'})
            sd = datetime.datetime.strptime(sd, "%Y-%m-%d")
            ed = datetime.datetime.strptime(ed, "%Y-%m-%d")
            # 入住天数
            days = (ed - sd)
            if sk == 'new':
                houses_order = House.objects.filter(area_id=aid,
                                                    max_days__gte=days,
                                                    min_days__lte=days,
                                                    order_count=0).order_by('-create_time')
            else:
                houses = House.objects.filter(area_id=aid,max_days__gte=days,min_days__lte=days)
                # 排序方式 booking(订单量), price-inc(低到高), price-des(高到低)
                if sk == 'booking':
                    houses_order = houses.order_by('-order_count')
                elif sk == 'price-inc':
                    houses_order = houses.order_by('price')
                elif sk == 'price-des':
                    houses_order = houses.order_by('-price')

        elif aid and not ed:
            # aid为真,ed为假
            try:
                house = House.objects.filter(area_id=aid)
            except Area.DoesNotExist:
                return JsonResponse({'errno': 400, 'errmsg': '没有房源'})
            # sd = time.strptime(sd, "%Y-%m-%d")
            # ed = time.strptime(ed, "%Y-%m-%d")
            # 入住天数
            # days = (ed - sd)
            if sk == 'new':
                houses_order = House.objects.filter(area_id=aid,
                                                    order_count=0).order_by('-create_time')
            else:
                houses = House.objects.filter(area_id=aid)
                # 排序方式 booking(订单量), price-inc(低到高), price-des(高到低)
                if sk == 'booking':
                    houses_order = houses.order_by('-order_count')
                elif sk == 'price-inc':
                    houses_order = houses.order_by('price')
                elif sk == 'price-des':
                    houses_order = houses.order_by('-price')

        elif ed and not aid:
            # ed为真,aid为假
            try:
                house = House.objects.all()
            except Area.DoesNotExist:
                return JsonResponse({'errno': 400, 'errmsg': '没有房源'})
            sd = datetime.datetime.strptime(sd, "%Y-%m-%d")
            ed = datetime.datetime.strptime(ed, "%Y-%m-%d")
            # 入住天数
            days = (ed - sd).days
            if sk == 'new':
                houses_order = House.objects.filter(max_days__gte=days,
                                                    min_days__lte=days,
                                                    order_count=0).order_by('-create_time')
            else:
                houses = House.objects.filter(max_days__gte=days, min_days__lte=days)
                # 排序方式 booking(订单量), price-inc(低到高), price-des(高到低)
                if sk == 'booking':
                    houses_order = House.objects.filter(max_days__gte=days,
                                                    min_days__lte=days).order_by('-order_count')
                elif sk == 'price-inc':
                    houses_order = House.objects.filter(max_days__gte=days,
                                                    min_days__lte=days).order_by('price')
                elif sk == 'price-des':
                    houses_order = House.objects.filter(max_days__gte=days,
                                                    min_days__lte=days).order_by('-price')
        else:
            try:
                houses = House.objects.all()
            except Area.DoesNotExist:
                return JsonResponse({'errno': 400, 'errmsg': '没有房源'})
            # sd = time.strptime(sd, "%Y-%m-%d")
            # ed = time.strptime(ed, "%Y-%m-%d")
            # 入住天数
            # days = (ed - sd)
            if sk == 'new':
                houses_order = House.objects.filter(order_count=0).order_by('-create_time')
            else:
                # 排序方式 booking(订单量), price-inc(低到高), price-des(高到低)
                if sk == 'booking':
                    houses_order = House.objects.all().order_by('-order_count')
                elif sk == 'price-inc':
                    houses_order = House.objects.all().order_by('price')
                elif sk == 'price-des':
                    houses_order = House.objects.all().order_by('-price')

        houses = []

        for house in houses_order:
            houses.append(
                {
                    "address": house.area.id,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": domain_name + house.index_image_url,
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": domain_name + str(house.user.avatar)
                    # "user_avatar": house.user.avatar.url
                }
            )
        total_page = len(houses)
        return JsonResponse({
                            "data": {
                                "houses": houses,
                                "total_page": total_page
                                    },
                            "errmsg": "请求成功",
                            "errno": "0"
                            })

# TODO 3.上传房源图片 POST √
from apps.houses import qiqiuyun
class HousesImageView(View):

    def post(self,request,house_id):
        house_image = request.FILES.get('house_image')

        # 2.验证参数
        if not house_image:
            return JsonResponse({'errno': 400, 'errmsg': '没有图片'})

        # 3.保存图片路径
        file_path = os.path.join(settings.BASE_DIR, 'media/%s' % house_image)
        with open(file_path, 'wb') as f:
            content = house_image.read()
            f.write(content)

            # 2.将参数保存起来
        try:
            house = House.objects.get(id=house_id)
        except House.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有该房子'})

        # 图片地址

        img_url,img_code = qiqiuyun.upload_img(bucked_name, file_path, domain_name)
        # 写入数据库
        House.objects.filter(id=house_id).update(index_image_url = img_code)
        HouseImage.objects.create(house = house,url = img_code)


        os.remove(file_path)

        print(img_url)

        return JsonResponse({
                            "data": {
                                "url": img_url
                            },
                            "errno": "0",
                            "errmsg": "图片上传成功"
                            })
# TODO 4.我的房屋列表 GET
class MyHouseListView(View):

    def get(self,request):
        # TODO 稍后写
        user = request.user
        # user = User.objects.get(id = 1)
        houses_list = House.objects.filter(user=user).order_by('-update_time')
        houses = []
        for house in houses_list:
            houses.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url": domain_name + house.index_image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                # TODO 登录用户之后使用
                "user_avatar": domain_name + str(house.user.avatar)
                # "user_avatar": house.index_image_url.url
            })

        return JsonResponse({
                            "data": {"houses": houses},
                            "errmsg": "ok",
                            "errno": "0"
                            })
# TODO 5.首页房屋推荐 GET
class IndexHouseView(View):
    def get(self,request):
        data = []
        houses_list = House.objects.all().order_by('-update_time')[0:5]
        for house in houses_list:
            data.append({
                "house_id": house.id,

                # "img_url":  house.index_image_url.url,

                "img_url":  domain_name + house.index_image_url,

                "title": house.title
                        })

        return JsonResponse({
                            "data": data,
                            "errmsg": "OK",
                            "errno": "0"
                            })
# TODO 7.房屋详情页面 GET
class MyhouseDetailView(View):
    def get(self,request,house_id):
        user = request.user
        if user:
            user_id = user.id
        else:
            user_id = -1
        try:
            house = House.objects.get(id = house_id)
        except House.DoesNotExist:
            return HttpResponseBadRequest('该房间不存在')
        orders_set = house.order_set.all()
        comments = []
        for order in orders_set:
            comments.append({
                        "comment": order.comment,
                        "ctime": order.create_time,
                        "user_name": order.user.username
                            })

        houses_image = HouseImage.objects.filter(house = house)
        img_urls = []
        for house_image in houses_image:
            img_urls.append(domain_name + house_image.url)

        facility_set = house.facility.values('id')
        facilities = []
        for facility_name in facility_set:
            facilities.append(facility_name['id'])
        house_data = {
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments,
                "deposit": house.deposit,
                "facilities": facilities,
                "hid": house.id,
                "img_urls": img_urls,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": domain_name + str(house.user.avatar),
                # "user_avatar": house.user.avatar.url,
                "user_id": user.id,
                "user_name": user.real_name
                }
        return JsonResponse({
                "data": {
                    "house": house_data,
                    "user_id": house.user.id
                },
                "errmsg": "OK",
                "errno": "0"
                })

